package com.byfan.barter.controller;

import com.byfan.barter.entity.Commodity;
import com.byfan.barter.entity.Favorites;
import com.byfan.barter.service.CommodityService;
import com.byfan.barter.service.FavoritesService;
import com.byfan.barter.utils.Message;
import com.byfan.barter.utils.MessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: FBY
 * @Description
 * @Version 1.0
 * @Date: 2021/5/16 14:34
 */
@Api(description = "收藏商品接口")
@RestController
@RequestMapping(value = "/favorites")
public class FavoritesController {
    @Autowired
    private FavoritesService favoritesService;

    @Autowired
    private CommodityService commodityService;

    @ApiOperation("添加收藏")
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Message save(Favorites favorites){
        Favorites f = favoritesService.save(favorites);
        return MessageUtil.success("添加成功",f);
    }

    @ApiOperation("根据收藏id取消收藏")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Message delete(Integer id){
        favoritesService.deleteById(id);
        return MessageUtil.success("已取消收藏");
    }

    @ApiOperation("根据用户openId和商品id取消收藏")
    @RequestMapping(value = "/deleteByOpenId",method = RequestMethod.POST)
    public Message deleteByOpenId(String openId,Integer commodityId){
        favoritesService.delete(openId,commodityId);
        return MessageUtil.success("已取消收藏");
    }

    @ApiOperation("根据id获取收藏信息")
    @RequestMapping(value = "/getById",method = RequestMethod.GET)
    public Message getById(Integer id){
        Favorites favorites = favoritesService.getById(id);
        return MessageUtil.success(favorites);
    }

    @ApiOperation("根据用户openId获取收藏列表")
    @RequestMapping(value = "/getByOpenId",method = RequestMethod.GET)
    public Message getByOpenId(String openId){
        List<Favorites> list = favoritesService.getByOpenId(openId);
        List<Map> result = new ArrayList<>();
        if (list==null){
            return MessageUtil.success("暂无数据");
        }else {
            for (Favorites favorites : list) {
                Map<String,Object> map = new HashMap<>();
                map.put("favorites",favorites);
                Commodity commodity = commodityService.getById(favorites.getCommodityId());
                map.put("commodity",commodity);
                result.add(map);
            }
        }

        return MessageUtil.success(result);
    }
}
